// pages/order_tj/order_tj.js
var app = getApp();
var utils = require('../../../utils/shop/formatShop.js');
var area = require('../../../utils/lib/area.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Kanjia_ID: 0, //砍价ID
    info: [], // 砍价信息
    back_address_id: 0, // 选择收货地址返回的地址id
    //收货地址信息
    address_info: {
      Address_ID: 0,
      Address_Name: '',
      Address_Mobile: '',
      Address_Province_name: '',   //名称
      Address_City_name: '',       //名称
      Address_Area_name: '',       //名称
      Address_Town_name: '',       //名称
      Address_Detailed: ''
    },
    shipping_list: [],  // 物流列表
    Shipping_ID: 0, // 选择的物流id
    shipping_idx: -1, // 选择物流下标
    total_shipping_fee: 0,  // 物流费用

    pay_total: 0, // 待支付金额

    pay_flag: false,
    payText: "立即付款",
    Order_ID: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.Kanjia_ID) {
      wx.showLoading({
        title: '加载中',
      });
      this.setData({
        Kanjia_ID: options.Kanjia_ID
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '缺少必要参数',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 1
          });
        }
      });
    }
  },

  //页面加载
  load: function() {
    wx.hideLoading();
    if (!app.globalData.userInfo) {
      app.login('', this.load);
      return false;
    }
    if (!app.globalData.shopConfig) {
      //获取商家配置信息
      app.getShopConfig(this.load);
      return false;
    }

    wx.showLoading({
      title: '加载中...',
    })

    // 查询砍价信息
    this.get_detail();
  },

  // 查询详情 
  get_detail: function (frist_kan_msg = true) {
    var transData = {
      act: 'get_kanjia_pro_detail',
      User_ID: app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID
    };
    app.http_req(transData, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0 && res.data && res.data.user_kanjia_id > 0) {
        var info = res.data;
        
        this.setData({
          info: info,
          pay_total: info.Cur_Price
        });

        if (info.Shipping == 1) {
          // 如果需要物流，查询收货地址
          this.get_address();
        } else {
          wx.hideLoading();
        }
        
      } else {
        wx.hideLoading();
        let msg = '查询砍价信息失败';
        if (typeof res.errorCode !== 'undefined' && res.errorCode == 0) {
          msg = '您还未开启砍价';
        } else if (typeof res.msg !== 'undefined') {
          msg = res.msg;
        }
        wx.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: function () {
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }

      // 结束下拉刷新
      utils.overPullDownRefresh();
    });
  },

  // 查询收货地址
  get_address () {
    var addressArgs = {
      act: 'get_address',
      User_ID: app.globalData.userInfo.User_ID,
    };
    if (this.data.back_address_id) {  //添加、选择收获地址返回
      addressArgs.Address_ID = this.data.back_address_id;
    } else if (this.data.address_info.Address_ID) { //有收获地址，则更新（防止收获地址编辑后返回）
      addressArgs.Address_ID = this.data.address_info.Address_ID;
    }
    app.http_req(addressArgs, app.globalData.init.api_url, 'POST', res => {
      if (this.data.back_address_id && res.errorCode != 0) {  //添加、选择收获地址返回
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '收获地址获取失败',
          showCancel: false
        });
        return false;
      }
      if (res.errorCode === 0) {
        var addresslist = res.data;
        if (typeof addresslist != 'undefined' && addresslist.length > 0) {  //有收货地址
          var addressInfo = '';
          if (this.data.back_address_id) {  //添加、选择收获地址返回
            addressInfo = addresslist[0];
          } else {
            //查询收货地址中的默认收货地址，没有默认则使用第一条收货地址
            for (var i in addresslist) {
              if (addresslist[i]['Address_Is_Default'] == 1) {
                addressInfo = addresslist[i];
              }
            }
            if (!addressInfo || addressInfo.length <= 0) {
              addressInfo = addresslist[0];
            }
          }

          this.setData({
            back_address_id: 0,   //清空数据
            address_info: addressInfo
          });
        }
      }

      // 查询物流
      this.get_shipping();
    });
  },

  // 查询物流
  get_shipping () {
    let post_data = {
      act: 'get_kanjia_shipping',
      User_ID: app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID,
      Shipping_ID: this.data.Shipping_ID,
      city_code: this.data.address_info.Address_City_code ? this.data.address_info.Address_City_code : 0
    };
    app.http_req(post_data, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        // 物流下标获取
        let shipping_idx = -1;
        for (let i in res.data.shipping_list) {
          if (res.data.shipping_list[i].Shipping_ID == res.data.Shipping_ID) {
            shipping_idx = i;
          }
        }
        this.setData({
          shipping_list: res.data.shipping_list,
          Shipping_ID: res.data.Shipping_ID,
          shipping_idx: shipping_idx,
          total_shipping_fee: res.data.total_shipping_fee,
          pay_total: res.data.pay_total
        });
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg !== 'undefined' ? res.msg : '查询物流信息失败',
          showCancel: false
        });
      }
    });
  },

  // 选择物流
  bindPickerChange (e) {
    let shipping_idx = e.detail.value;
    let old_Shipping_ID = this.data.Shipping_ID;
    let Shipping_ID = this.data.shipping_list[shipping_idx].Shipping_ID;
    this.setData({
      shipping_idx: shipping_idx,
      Shipping_ID: Shipping_ID
    });
    //选择不同的物流模版，重新计算价格
    if (Shipping_ID != old_Shipping_ID) {
      this.get_shipping();
    }
  },

  //收货地址跳转
  address: function (e) {
    //判断是添加还是选择
    var address_id = e.currentTarget.dataset.addressid;
    wx.navigateTo({
      url: address_id ? '/pages/addresslist/addresslist?from=checkout&addressid=' + address_id : '/pages/addressaddedit/addressaddedit?from=checkout'
    });
  },

  //提交地址
  formSubmit: function(e) {
    var input = e.detail.value;

    // 判断需要物流时是否选择收货地址
    if (this.data.info.Shipping == 1) {
      if (this.data.address_info.Address_ID <= 0) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return false;
      }
      if (this.data.Shipping_ID <= 0) {
        wx.showToast({
          title: '请选择物流',
          icon: 'none'
        });
        return false;
      }
    }
    
    let post_data = {
      act: 'kanjian_tj',
      User_ID: app.globalData.userInfo.User_ID,
      Kanjia_ID: this.data.Kanjia_ID,
      Address_ID: this.data.address_info.Address_ID,
      Shipping_ID: this.data.Shipping_ID,
      remark: input.remark
    };
    this.setData({
      pay_flag: true
    });
    app.http_req(post_data, app.globalData.init.api_url, 'POST', this.payOrder);
  },

  // 提交订单回调
  payOrder(res){
    this.setData({
      pay_flag: false
    });
    let that = this;
    if (res.errorCode == 0) {
      if (res.action != 'callback') { //立即购买提交后不支付，后点击继续支付
        that.setData({
          Order_ID: res,
          payText: '去支付'
        });
      }
      if (that.data.Order_ID.data.Order_Status == 0) {
        wx.showToast({
          title: '订单提交成功，等待商家确认',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/orderlist/orderlist?order_type=' + that.data.Order_ID.data.Order_Type
              });
            }, 1000);
          }
        });
      } else {
        var postData = {
          Order_ID: that.data.Order_ID.data.Order_ID,
          Order_Type: that.data.Order_ID.data.Order_Type
        };
        app.orderAction('pay_checkout', postData, that.payOrder);
      }
    } else {
      wx.showModal({
        title: '提示',
        content: typeof res.msg != 'undefined' ? res.msg : '提交失败',
        showCancel: false
      });
    }
  },

  onShow: function () {
    this.load();
  }
})